package ru.spb.osll.myfit.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

import java.io.IOException;
import java.io.FileNotFoundException;

public class FileUtils {
	/*
         * Copy everything from srcDir to destDir
	 */
	public static void copyDirectory(String srcDir, String destDir) throws FileNotFoundException, IOException {
		File base = new File(srcDir);
		if(base.isDirectory())
			shareDirectorys(base, destDir);
		else
			copyFile(base, destDir);
	}

	private static void shareDirectorys(File srcDir, String destDir) throws FileNotFoundException, IOException {
		File[] filesIn = srcDir.listFiles();
		for(int i = 0; i < filesIn.length; i++)
			if(filesIn[i].isDirectory())
				shareDirectorys(filesIn[i], destDir + "/" + filesIn[i].getName());
			else
				copyFile(filesIn[i], destDir);
	}

	private static void copyFile(File file, String destDir) throws FileNotFoundException, IOException {
		File newFile = new File(destDir + "/" + file.getName());
		File directory = new File(newFile.getParent());
		directory.mkdirs();

		FileInputStream src = new FileInputStream(file);
		FileOutputStream dst = new FileOutputStream(newFile);

		FileChannel srcCh = src.getChannel();
		FileChannel dstCh = dst.getChannel();
		
		srcCh.transferTo(0, srcCh.size(), dstCh);
		srcCh.close();
		dstCh.close();
		dst.close();
		src.close();
	}
}
